//
//  NSDictionary+JSONReadWrite.m
//  MGPolymerAdSDK
//
//  Created by 虞嘉伟 on 2025/1/16.
//  
  

#import "NSDictionary+JSONReadWrite.h"

@implementation NSDictionary (JSONReadWrite)

/// 读取JSON数据
+ (NSDictionary *)JSONWithContentsOfFile:(NSString *)filePath {
    if (![NSFileManager.defaultManager fileExistsAtPath:filePath]) {
        return nil;
    }
    NSError *error = nil;
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath options:0 error:&error];
    if (!jsonData) {
        NSLog(@"NSDictionary无法读取文件: %@, 错误: %@", filePath, error.localizedDescription);
        return nil;
    }
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    if (!json) {
        NSLog(@"JSON解析NSDictionary失败: %@", error.localizedDescription);
        return nil;
    }
    return json;
}

/// 写入JSON数据
- (BOOL)writeToJSONFile:(NSString *)filePath atomically:(BOOL)atomically {
    NSDictionary *json = self ?: @{};
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"JSON序列化NSDictionary失败: %@", error.localizedDescription);
        return NO;
    }
    BOOL res = [jsonData writeToFile:filePath atomically:YES];
    NSLog(@"--->JSON写入NSDictionary: %@ 路径: %@", res ? @"成功" : @"失败", filePath);
    return res;
}


@end

